<?php
/**
 * Created by PhpStorm.
 * User: tom_xia
 * Date: 2018/8/29
 * Time: 18:27
 */
require_once dirname(__DIR__) . "/common.php";
use app\cls\tom\JsSDK;
use app\cls\tom\Response;
use app\cls\tom\SysResource;
use app\cls\tom\Tools;

$dataStr = file_get_contents("php://input");
if(empty($dataStr)){
    Response::badRequest();
}
$data = @json_decode($dataStr,true);
if(empty($data)){
    Response::badRequest();
}
if(empty($data["material_id"])){
    Response::badRequest();
}
$fileNameKey = md5($dataStr);
$urlKey = REDIS_PREFIX."material_poster_{$fileNameKey}";
$redis = SysResource::getRedis();
$url = $redis->get($urlKey);
if($url){
    Response::output(0,"ok",["file_path"=>$url]);
}else{
    $savePath = CDN_PATH."/poster_qrcode/";
    $saveFile = $savePath.$fileNameKey.".png";
    if(!file_exists($savePath)){
        $isCreateSuccess = mkdir($savePath,0777,true);
        if(!$isCreateSuccess){
            Response::output(-1,"服务器内部异常-内部权限不足");
        }
    }
    if(file_exists($saveFile) &&  filesize($saveFile) >0){
        $url = str_replace(CDN_PATH,CDN_HOST,$saveFile);
    }else{

        $materialId = $data["material_id"];
        unset($data["material_id"]);
        $newDataStr = json_encode($data);
        $url = "";

        $appKey = WX_PUBLIC_APP_ID;
        $appSecret = WX_PUBLIC_APP_SECRECT;

        $jssdk = new JsSDK($appKey, $appSecret);
        try{
            $accessToken = $jssdk->getAccessToken();
            $data  = http_build_query($data);
            $re = Tools::curl("https://api.weixin.qq.com/wxa/getwxacode?access_token={$accessToken}",$newDataStr,"post",false,["Content-Type:application/json"]);
            $res = @json_decode($re,true);
            if($res && isset($res["errcode"])){
                Response::output(-1,"请求失败 msg==>{$res["errcode"]}:{$res["errmsg"]}");
            }
            file_put_contents($saveFile,$re);
            if(file_exists($saveFile) && filesize($saveFile) >0){
                $url = str_replace(CDN_PATH,CDN_HOST,$saveFile);
            }else{
                Response::output(-1,"服务器内部异常-写存储异常");
            }
        }catch (\Exception $e){
            Response::output(-1,"请求失败 msg==>".$e->getMessage());
        }
    }
    $redis->setex($urlKey,10*60,$url);
    Response::output(0,"ok",["file_path"=>$url]);
}